//
//  DesignAppointmentViewController.m
//  customer
//
//  Created by Holothurian on 2018/10/21.
//  Copyright © 2018年 yinlong. All rights reserved.
//

#import "DesignAppointmentViewController.h"
#import "DecorateAppointMultiTableViewCell.h"
#import "AppointmentCenterViewController.h"
#import "CouponListModel.h"

static NSString *DefaultIDentifier = @"DefaultIDentifier";
static NSString *TapSelectIDentifier = @"TapSelectIDentifier";
static NSString *Square2IDentifier = @"Square2IDentifier";
static NSString *InputTextIDentifier = @"InputTextIDentifier";
static NSString *PositionSelectIDentifier = @"PositionSelectIDentifier";
@interface DesignAppointmentViewController ()<UIScrollViewDelegate,UITableViewDelegate,UITableViewDataSource,DecorateTapSelectTableCellDelegate>

@property (nonatomic,strong)NSString *moneyString;
@property (nonatomic,strong)CouponListModel *couponModel;

@property (nonatomic,strong)AdvertiseView *adV;

@property (nonatomic,strong)UIScrollView *scrollView;

@property (nonatomic,strong)NSMutableArray *keyArray;

@property (nonatomic,strong)NSMutableArray *valueArray;

@property (nonatomic,strong)NSMutableArray *placeArray;

/**
 装修风格
 */
@property (nonatomic,strong)NSMutableArray *styleArray;

@property (nonatomic,strong)NSMutableArray *stylePickerArr;

/**
 当前选中的model
 */
@property (nonatomic,strong)AppointmentModel *selectStyleModel;


@property (nonatomic,strong)DecorateLocationModel *locationModel;

@end

@implementation DesignAppointmentViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self createView];
    [self loadDataSource];
}





- (void)loadDataSource{
    AutoWeakSelf
    [[QYNetManager sharedManager]POST:kRenovationStyles parameters:nil andApiTyp:CustomerApiTypGetOrders SuccessBlock:^(id responseObject) {
        [weakSelf hideLoading];
        if ([responseObject[@"status"] isEqualToString:@"error"]) {
            [weakSelf showErrorTipWithTitle:responseObject[@"error"]];
        }else{
            NSArray *dataSource = responseObject[@"data"];
            for (NSDictionary *dict in dataSource) {
                AppointmentModel *model = [AppointmentModel yy_modelWithDictionary:dict];
                [weakSelf.styleArray addObject:model];
                [weakSelf.stylePickerArr addObject:model.style_name];
            }
        }
    } Failure:^(NSError *error) {
        [weakSelf hideLoading];
        [weakSelf showErrorTipWithTitle:CustomerPoolNetStr];
    }];
}

- (void)createView{
    self.title = @"设计预约";
    [self.view addSubview:self.scrollView];
    if (!self.adV) {
        self.adV = [self bannerView];
    }
    [self.scrollView addSubview:self.adV];
    [self refreshBanner:self.adV];
    
    self.tableView.frame = CGRectMake(0, self.adV.viewBottom + 10, F_DEVICE_W, 400);
    self.tableView.bounces = NO;
    [self.tableView registerClass:[DecorateAppointDefaultTableCell class] forCellReuseIdentifier:DefaultIDentifier];
    [self.tableView registerClass:[DecorateAppointTapSelectTableCell class] forCellReuseIdentifier:TapSelectIDentifier];
    [self.tableView registerClass:[DecorateAppointSquare2TableCell class] forCellReuseIdentifier:Square2IDentifier];
    [self.tableView registerClass:[DecorateAppointInputTextTableCell class] forCellReuseIdentifier:InputTextIDentifier];
    [self.tableView registerClass:[DecorateAppointPositionSelectTableCell class] forCellReuseIdentifier:PositionSelectIDentifier];
    [self.scrollView addSubview:self.tableView];
    
    UIButton *appointButton = [UIButton buttonWithType:UIButtonTypeCustom];
    appointButton.frame = CGRectMake(30, F_DEVICE_H - NAVIGATION_BAR_HEIGHT - bottomPadding(20), F_DEVICE_W - 60, 50);
    appointButton.layer.cornerRadius = 6;
    appointButton.layer.masksToBounds = YES;
    [appointButton setBackgroundColor:[HSPublic colorWithHexString:@"333333"]];
    [appointButton setImage:[UIImage imageNamed:@"designAppointment"] forState:UIControlStateNormal];
    [appointButton setImage:[UIImage imageNamed:@"designAppointment"] forState:UIControlStateSelected];
    [appointButton setTitle:@"立即预约" forState:UIControlStateNormal];
    [appointButton setTitle:@"立即预约" forState:UIControlStateSelected];
    [appointButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [appointButton setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
    [appointButton addTarget:self action:@selector(getTheCouponModelInfor) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:appointButton];
    
    [self.keyArray addObjectsFromArray:@[@"选择类型",@"房屋面积",@"联系人",@"联系电话",@"所在地区",@"详细地址",@"设计报价"]];
    [self.placeArray addObjectsFromArray:@[@"点击选择类型",@"请输入房屋面积",@"请输入姓名",@"请输入手机号码",@"点击选择地址",@"街道名称门牌号",@"0"]];
    [self.valueArray addObjectsFromArray:@[@"",@"",@"",@"",@"",@"",@""]];
    self.locationModel = [[DecorateLocationModel alloc]init];
}

- (AdvertiseView *)bannerView{
    return [[AdvertiseView alloc]initWithFrame:CGRectMake(0, 0, f_Ad_Content_W, f_Ad_Content_H)];
}



#pragma mark - - 根据场景获取优惠券
-(void)getTheCouponModelInfor{
    AutoWeakSelf
    
    if (!self.selectStyleModel || k_Is_Empty(self.valueArray[0])) {
        [self showErrorTipWithTitle:@"请选择类型"];
        return;
    }
    if (k_Is_Empty(self.valueArray[1])) {
        [self showErrorTipWithTitle:@"请输入房屋面积"];
        return;
    }
    
    NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithCapacity:0];
    [dict setObject:[NSString emptyStr:K_UserDefault_Read(CustomerUserAccount)] forKey:@"member_account"];
    [dict setObject:[NSNumber numberWithDouble:self.moneyString.doubleValue] forKey:@"fee"];
    [dict setObject:[NSNumber numberWithInt:2] forKey:@"use_scene"];

    
    [[QYNetManager sharedManager]POST:kGetCanUserCoupon parameters:dict andApiTyp:CustomerApiTypGetOrders SuccessBlock:^(id responseObject) {
        [weakSelf hideLoading];
        if ([responseObject[@"status"] isEqualToString:@"error"]) {
            [weakSelf showErrorTipWithTitle:responseObject[@"error"]];
        }else if ([responseObject[@"status"] isEqualToString:@"pending"]|| [responseObject[@"data"] isKindOfClass:[NSNull class]]){
            [weakSelf showErrorTipWithTitle:responseObject[@"error"]];
        }else if ([[NSString stringWithFormat:@"%@",responseObject[@"success"]] isEqualToString:@"1"]){
            NSDictionary *data = responseObject[@"data"];
            if (![data isKindOfClass:[NSNull class]] && [data isKindOfClass:[NSDictionary class]] && [data count]){
                weakSelf.couponModel = [CouponListModel yy_modelWithJSON:data];
                [weakSelf appointmentAction];
            }else{
                NSLog(@"暂无优惠券可用");
                [weakSelf appointmentAction];
            }
        }else{
            [weakSelf showErrorTipWithTitle:responseObject[@"error"]];
        }
    } Failure:^(NSError *error) {
        [weakSelf hideLoading];
        [weakSelf showErrorTipWithTitle:CustomerPoolNetStr];
    }];
}

- (void)appointmentAction{
    AutoWeakSelf
    if (!self.selectStyleModel || k_Is_Empty(self.valueArray[0])) {
        [self showErrorTipWithTitle:@"请选择类型"];
        return;
    }
    if (k_Is_Empty(self.valueArray[1])) {
        [self showErrorTipWithTitle:@"请输入房屋面积"];
        return;
    }
    if (k_Is_Empty(self.valueArray[2])) {
        [self showErrorTipWithTitle:@"请输入联系人姓名"];
        return;
    }
    if (k_Is_Empty(self.valueArray[3]) && [self.valueArray[3] length] != 11) {
        [self showErrorTipWithTitle:@"请输入正确的手机号码"];
        return;
    }
    if (k_Is_Empty(self.valueArray[4]) || !self.locationModel) {
        [self showErrorTipWithTitle:@"请选择地址"];
        return;
    }
    if (k_Is_Empty(self.valueArray[5])) {
        [self showErrorTipWithTitle:@"请填写街道名称门牌号"];
        return;
    }
    
    NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithCapacity:0];
    [dict setObject:[NSString emptyStr:K_UserDefault_Read(CustomerUserID)] forKey:@"member_id"];
    [dict setObject:[NSString emptyStr:K_UserDefault_Read(CustomerUserToken)] forKey:@"member_token"];
    [dict setObject:@"2" forKey:@"order_type"];//1:装修预约 2:设计预约
    [dict setObject:self.selectStyleModel.style_id forKey:@"style_id"];//风格id
    [dict setObject:self.valueArray[1] forKey:@"order_area"];//订单面积
    [dict setObject:self.valueArray[2] forKey:@"contact_name"];//联系人姓名
    [dict setObject:self.valueArray[3] forKey:@"contact_mobile"];//联系人电话
    [dict setObject:self.locationModel.province?:@"" forKey:@"address_provider"];//省
    [dict setObject:self.locationModel.city?:@"" forKey:@"address_city"];//市
    [dict setObject:self.locationModel.country?:@"" forKey:@"address_country"];//区
    [dict setObject:self.valueArray[5]?:@"" forKey:@"address_detail"];//详情地址

    [[QYNetManager sharedManager]POST:kInsertRenovationOrder parameters:dict andApiTyp:CustomerApiTypGetOrders SuccessBlock:^(id responseObject) {
        [weakSelf hideLoading];
        if ([responseObject[@"status"] isEqualToString:@"error"]) {
            [weakSelf showErrorTipWithTitle:responseObject[@"error"]];
        }
        else if ([responseObject[@"status"] isEqualToString:@"pending"]|| [responseObject[@"data"] isKindOfClass:[NSNull class]]){
            [weakSelf showErrorTipWithTitle:responseObject[@"error"]];
        }else{
            NSString *status = [NSString stringWithFormat:@"%@",responseObject[@"status"]];
            if ([status isEqualToString:@"ok"]) {
                //[weakSelf useMyCouponWithOrderId:result];
                if (k_Is_Empty(weakSelf.couponModel.rule)) {
                        SLog(@"提交订单时无优惠券使用")
                }else{
                    //满减券
                    SLog(@"rule = %@ money = %@",weakSelf.couponModel.rule,weakSelf.couponModel.money);
                    if ([weakSelf.couponModel.rule isEqualToString:@"1"]) {
                        SLog(@"实际金额：%@",[NSString stringWithFormat:@"%@",[NSNumber numberWithDouble:weakSelf.moneyString.doubleValue - weakSelf.couponModel.money.doubleValue]]);
                    }else{
                        //折扣券
                        SLog(@"实际金额：%@",[NSString stringWithFormat:@"%@",[NSNumber numberWithDouble:weakSelf.moneyString.doubleValue - (weakSelf.couponModel.money.doubleValue)*weakSelf.moneyString.doubleValue]]);
                    }
                }
                [weakSelf showSubmitSuccessPageWithTitle:@"设计预约成功" Somebody:@"客服联系" ButtonTitle:@""];
            }else{
                [weakSelf showErrorTipWithTitle:@"预约失败"];
            }
        }
    } Failure:^(NSError *error) {
        [weakSelf hideLoading];
        [weakSelf showErrorTipWithTitle:CustomerPoolNetStr];
    }];
    
}

#pragma mark - - 下单成功之后调用此处的使用优惠券接口
- (void)useMyCouponWithOrderId:(NSString *)orderId {
    
    AutoWeakSelf;
    if (self.couponModel != nil) {
        NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithCapacity:0];
        //[dict setObject:[NSString emptyStr:K_UserDefault_Read(CustomerUserID)] forKey:@"member_id"];
        //[dict setObject:[NSString emptyStr:K_UserDefault_Read(CustomerUserToken)] forKey:@"member_token"];
        [dict setObject:orderId forKey:@"order_id"];
        [dict setObject:@"2" forKey:@"order_type"];
        [dict setObject:@"2" forKey:@"flag"];
        [dict setObject:self.couponModel.coupon_id?:@"" forKey:@"id"];
        
        [[QYNetManager sharedManager]POST:kUseCoupon parameters:dict andApiTyp:CustomerApiTypGetOrders SuccessBlock:^(id responseObject) {
            if ([responseObject[@"status"] isEqualToString:@"error"]) {
                [weakSelf showErrorTipWithTitle:responseObject[@"error"]];
            }
            else if ([responseObject[@"status"] isEqualToString:@"pending"]|| [responseObject[@"data"] isKindOfClass:[NSNull class]]){
                [weakSelf showErrorTipWithTitle:responseObject[@"error"]];
            }else{
                NSInteger result = [responseObject[@"status"] integerValue];
                if (result) {
                    //展示预约成功界面
                    [weakSelf showSubmitSuccessPageWithTitle:@"设计预约成功" Somebody:@"客服联系" ButtonTitle:@""];
                }else{
                    [weakSelf showErrorTipWithTitle:@"预约失败"];
                }
            }
        } Failure:^(NSError *error) {
            [weakSelf hideLoading];
            [weakSelf showErrorTipWithTitle:CustomerPoolNetStr];
        }];
    }else{
        [weakSelf showSubmitSuccessPageWithTitle:@"设计预约成功" Somebody:@"客服联系" ButtonTitle:@""];
    }
}


/**
查看预约 
 */
- (void)checkOutAppointment{
    AppointmentCenterViewController *orderVC = [[AppointmentCenterViewController alloc]init];
    orderVC.selectIndex = 1;
    TAB_PUSH(self, orderVC, YES);
}

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [self.keyArray count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 0) {
        DecorateAppointTapSelectTableCell *cell = [self.tableView dequeueReusableCellWithIdentifier:TapSelectIDentifier];
        cell.nameLabel.text = self.keyArray[indexPath.row];
        [cell cellForLayout:self.valueArray[indexPath.row]];
        cell.delegate = self;
        return cell;
    }else if (indexPath.row == 1){
        DecorateAppointSquare2TableCell *cell = [self.tableView dequeueReusableCellWithIdentifier:Square2IDentifier];
        cell.delegate = self;
        cell.indexPath = indexPath;
        cell.squareLabel.text = @"m²";
        cell.nameLabel.text = self.keyArray[indexPath.row];
        cell.squareTextField.text = self.valueArray[indexPath.row];
        cell.squareTextField.placeholder = self.placeArray[indexPath.row];
        [cell.squareTextField setValue:[HSPublic colorWithHexString:@"B2B2B2"] forKeyPath:@"_placeholderLabel.textColor"];
        return cell;
    }else if (indexPath.row == 2 || indexPath.row == 3 || indexPath.row == 5){
        DecorateAppointInputTextTableCell *cell = [self.tableView dequeueReusableCellWithIdentifier:InputTextIDentifier];
        cell.indexPath = indexPath;
        cell.delegate = self;
        cell.nameLabel.text = self.keyArray[indexPath.row];
        cell.textField.placeholder = self.placeArray[indexPath.row];
        cell.textField.text = self.valueArray[indexPath.row];
        [cell.textField setValue:[HSPublic colorWithHexString:@"B2B2B2"] forKeyPath:@"_placeholderLabel.textColor"];
        return cell;
    }else if (indexPath.row == 4){
        DecorateAppointPositionSelectTableCell *cell = [self.tableView dequeueReusableCellWithIdentifier:PositionSelectIDentifier];
        cell.nameLabel.text = self.keyArray[indexPath.row];
        [cell cellForLayout:self.valueArray[indexPath.row]];
        cell.delegate = self;
        return cell;
    }else if(indexPath.row == 6){
        DecorateAppointDefaultTableCell *cell = [self.tableView dequeueReusableCellWithIdentifier:DefaultIDentifier];
        cell.nameLabel.text = self.keyArray[indexPath.row];
        if (k_Is_Empty(self.valueArray[1])|| !self.selectStyleModel) {
            cell.detailNameLabel.text = @"0元";
            cell.detailNameLabel.textColor = [HSPublic colorWithHexString:@"B2B2B2"];
        }else{
            CGFloat stylePrice =  [self.selectStyleModel.style_price floatValue];
            CGFloat square = [self.valueArray[1]floatValue];
            cell.detailNameLabel.text = [NSString stringWithFormat:@"%.2f元",stylePrice * square];
            self.moneyString = [NSString stringWithFormat:@"%.2f",stylePrice * square];
            cell.detailNameLabel.textColor = [HSPublic colorWithHexString:@"333333"];
        }
        return cell;
    }else{
        DecorateAppointDefaultTableCell *cell = [self.tableView dequeueReusableCellWithIdentifier:DefaultIDentifier];
        cell.nameLabel.text = self.keyArray[indexPath.row];
        cell.detailNameLabel.text = self.valueArray[indexPath.row];
        return cell;
    }
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 50.f;
}

#pragma mark - DecorateTapSelectTableCellDelegate
/**
 类型选择
 */
- (void)tapSelectTableCellEventWithIndexPath:(NSIndexPath *)indexPath{
    NSLog(@"点击选择类型");
    
    HSPickerView *pickView = [[HSPickerView alloc] init];
    pickView.components = 1;
    NSArray *dataArr = @[self.stylePickerArr];
    
    pickView.pickViewArr = dataArr;
    AutoWeakSelf
    [pickView didFinishSelectedDate:^(NSArray *selectIndexs) {
        NSInteger selectIndex = [[selectIndexs objectAtIndex:0] integerValue];
        NSArray *arr = [dataArr objectAtIndex:0];
        weakSelf.selectStyleModel = weakSelf.styleArray[selectIndex];
        [weakSelf.valueArray replaceObjectAtIndex:0 withObject:[arr objectAtIndex:selectIndex]];
        [weakSelf.tableView reloadData];
    }];
}

/**
 地址选择
 */
- (void)tapPlaceTableCellEvent{
    [self.view endEditing:YES];
    NSLog(@"点击选择地址");
    BaseLocationManagerVC *location = [[BaseLocationManagerVC alloc]init];
    AutoWeakSelf
    location.locationBlock = ^(DecorateLocationModel *locationModel) {
        weakSelf.locationModel = locationModel;
        [weakSelf.valueArray replaceObjectAtIndex:4 withObject:weakSelf.locationModel.prefixArea];
        [weakSelf.valueArray replaceObjectAtIndex:5 withObject:weakSelf.locationModel.suffixArea];
        [weakSelf.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:4 inSection:0],[NSIndexPath indexPathForRow:5 inSection:0]] withRowAnimation:UITableViewRowAnimationAutomatic];
    };
    TAB_PUSH(self, location, YES);
}

- (void)modifSingleTextFieldTableCell:(NSIndexPath *)indexPath WithEditEndText:(NSString *)text{
    if (k_Is_Empty(text)) {
        return;
    }
    if (k_Is_Empty(self.couponModel.rule)) {
        [self.valueArray replaceObjectAtIndex:indexPath.row withObject:text];

    }else{
        //满减券
        SLog(@"rule = %@ money = %@",self.couponModel.rule,self.couponModel.money);
        if ([self.couponModel.rule isEqualToString:@"1"]) {
            [self.valueArray replaceObjectAtIndex:indexPath.row withObject:[NSString stringWithFormat:@"%@",[NSNumber numberWithDouble:text.doubleValue - self.couponModel.money.doubleValue]]];
        }else{
            //折扣券
            [self.valueArray replaceObjectAtIndex:indexPath.row withObject:[NSString stringWithFormat:@"%@",[NSNumber numberWithDouble:text.doubleValue - (self.couponModel.money.doubleValue)*text.doubleValue]]];
        }
    }
    [self.tableView reloadData];
}


#pragma mark - GETTER
- (UIScrollView *)scrollView{
    if (!_scrollView) {
        _scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0,NAVIGATION_BAR_HEIGHT, F_DEVICE_W, F_DEVICE_H - NAVIGATION_BAR_HEIGHT - bottomPadding(0))];
        _scrollView.delegate = self;
        _scrollView.contentSize = CGSizeMake(F_DEVICE_W,f_Ad_Content_H + 500);
    }
    return _scrollView;
}

- (NSMutableArray *)keyArray{
    if (!_keyArray) {
        _keyArray = [NSMutableArray array];
    }
    return _keyArray;
}

- (NSMutableArray *)valueArray{
    if (!_valueArray) {
        _valueArray = [NSMutableArray array];
    }
    return _valueArray;
}

- (NSMutableArray *)placeArray{
    if (!_placeArray) {
        _placeArray = [NSMutableArray array];
    }
    return _placeArray;
}

- (NSMutableArray *)styleArray{
    if (!_styleArray) {
        _styleArray = [NSMutableArray array];
    }
    return _styleArray;
}

- (NSMutableArray *)stylePickerArr{
    if (!_stylePickerArr) {
        _stylePickerArr = [NSMutableArray array];
    }
    return _stylePickerArr;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
